package cn.yi.newsys.service.impl;

import java.util.List;

import cn.yi.newsys.dao.NewsDao;
import cn.yi.newsys.dao.impl.NewsDaoImpl;
import cn.yi.newsys.pojo.News;
import cn.yi.newsys.pojo.PageBean;
import cn.yi.newsys.service.NewsService;

/**
 * 新闻逻辑业务实现类
 * @author Lenovo
 *
 */
public class NewsServiceImpl implements NewsService{

	private NewsDao nd = new NewsDaoImpl();
	
	@Override
	public List<News> showNews() {
		return nd.getIndexNews() ;
	}

	@Override
	public List<News> showInlandNews() {
		return nd.getAllInlandNews() ;
	}

	@Override
	public News getNewByID(int num) {
		return nd.getNewsByID(num);
	}

	@Override
	public List<News> getSearchNews(String str) {
		return nd.getSerachNews(str) ;
	}

	@Override
	public List<News> getAllNews() {
		return nd.getAllNews() ;
	}

	@Override
	public int addNews(News news) {
		int i = -1 ;
		News n = nd.getNewsByName(news.getTittle()) ;
		if(n == null){
			i = nd.addNews(news) ;
		}
		return i ;
	}

	@Override
	public int queryTotalRecord(String searchTitle , int seachTid) {
		
		try {
			return nd.queryTotalRecord(searchTitle , seachTid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0 ;
	}

	@Override
	public PageBean<News> getAllNews(int pageNum, int pageSize , String searchTitle , int searchTid) {
		PageBean<News> pageBean = new PageBean<News>() ;
		// 根据页码和每页记录数来计算偏移量
		int offset = (pageNum-1)*pageSize ;
		List<News> list = nd.getAllNews(offset,pageSize,searchTitle ,searchTid) ;	
		// 得到新闻的总数量
		int totalCount = this.queryTotalRecord(searchTitle , searchTid) ;
		// 计算总页数
		pageBean.setTotalCount(totalCount) ;
		// 设置当前页码
		pageBean.setCurrPageNo(pageNum) ;
		// 设置每页的记录数
		pageBean.setPageSize(pageSize) ;
		// 数据保存到  pageBen 的集合中
		pageBean.setLisr(list);
		return  pageBean ;
	}

	@Override
	public int queryTotalPage(int pageSize , String searchTitle , int seachTid) {
		int pageCount = 0 ;
		// 获取总数据量
		int totalNews = queryTotalRecord(searchTitle , seachTid) ;
		int temp = totalNews / pageSize ;
		if(totalNews > 0){
			pageCount = totalNews%pageSize == 0 ? temp : temp + 1 ;
		}
		return pageCount;
	}

	@Override
	public boolean delNews(int newsId) {
		int row = nd.delNews(newsId) ;
		if(row == 0){
			return false ;
		}else{
			return true ;
		}
	}

}
